package com.lee.hystrix.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * <br/>
 *
 * @author liyuanchang
 * @version V1.0
 * @email liyuanchang@chinamobile.com
 * @date 2019/6/20 16:43
 */
public class Utils {
    public static String string2Html(String str) {
        return str.replaceAll("\n", "<br/>").replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
    }

    public static List<String> future2List(List<Future<String>> futures) {
        List<String> list = new ArrayList<>();

        while (futures.size() > 0) {
            Iterator<Future<String>> it = futures.iterator();
            while (it.hasNext()) {
                Future<String> next = it.next();
                if (next.isDone()) {// 处理已经完成的，没完成的留给下一个迭代
                    try {
                        list.add(next.get());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    it.remove();
                }
            }
            // System.out.println("futures.size() = " + futures.size() + ", list.size() = " + list.size());
        }

        return list;
    }

    public static String list2String(List<String> list) {
        StringBuilder sb = new StringBuilder();
        list.forEach(sb::append);
        return sb.toString();
    }

    public static void sleep(int milliseconds) {
        try {
            TimeUnit.MILLISECONDS.sleep(milliseconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
